/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.wii.elpro.web.action;

import com.wii.elpro.dao.UserDAOInterface;
import com.wii.elpro.dao.hb.UserDAOImpl;
import com.wii.elpro.entity.User;
import com.wii.elpro.web.form.UserLoginForm;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

/**
 *
 * @author hp02
 */
public class UserLoginAction extends Action {

    public UserLoginAction() {
    }
    
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) throws Exception {
        
        String forward;        
        UserLoginForm loginForm = (UserLoginForm) form;
        UserDAOInterface dao = new UserDAOImpl();
        ActionMessages messages = null;
        try {
            User users = dao.login(loginForm.getUsername(), loginForm.getPassword());
            if (users==null) {
                messages = new ActionMessages();
                messages.add("customMessage", new ActionMessage("customMessage", "Invalid user name and password"));
                forward = "fail";
            } else {
//                messages = new ActionMessages();
//                messages.add("customMessage", new ActionMessage("customMessage", "Welcome "+user.getNama()+" and Happy Working!"));
//                saveMessages(request, messages);
                HttpSession sess = request.getSession(true);
                sess.setAttribute("statusMenu",users.getDepartemen().getKode());
                sess.setAttribute("userSession", users);
                forward = "success";
            }
        } catch (Exception e) {
            messages = new ActionMessages();
            messages.add("customMessage", new ActionMessage("customMessage", "Data source is not found. Please contact my developer."));
            forward = "fail";
            e.printStackTrace();
        }
        saveMessages(request, messages);
        return mapping.findForward(forward);
    }
}
